<template>
  <div ref="chart" :style="{ width: '60vw', height: '40vh' }"></div>
</template>
<script lang="ts" setup>
import * as echarts from "echarts";
import { onMounted, nextTick, ref } from "vue";
import { salaryforYear, SeriesItem } from "../api/function";

const chart = ref<HTMLElement | null>(null); // 图表
const legendData: string[] = []; // 图例数据
const seriesData: SeriesItem[] = []; // 折线数据
let yearData: string[] = [];

// 获取折线图数据
const getSalaryforYear = async () => {
  const res = await salaryforYear();
  console.log("折线图数据", res.data);

  legendData.splice(
    0,
    legendData.length,
    ...res.data.map((item) => item.position.trim())
  );
  seriesData.splice(0, seriesData.length, ...res.data); // 不需要 map 处理
  yearData = res.data[0].salaries.map((item) => String(item.year));

  // series配置项信息
  const series = seriesData.map((item: SeriesItem) => ({
    name: item.position,
    type: "line",
    data: item.salaries.map((salaryItem) => salaryItem.salary),
  }));
  // 调用图表更新函数
  updateChart(series);
};

// 更新图表函数
const updateChart = (series: any) => {
  if (chart.value) {
    const myChart = echarts.init(chart.value);
    myChart.clear();
    myChart.setOption({
      title: {
        text: "2014-2024年计算机岗位薪资变化（单位：元）",
        left: "3%",
        textStyle: {
          color: "#b8b4b4",
          fontSize: "13px",
        },
        // top: "-5%",
      },
      tooltip: {
        trigger: "axis",
      },
      legend: {
        data: legendData,
        top: "7%",
        right: "1%",
        // 字体颜色
        textStyle: {
          color: "#b8b4b4",
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },

      xAxis: {
        type: "category",
        boundaryGap: false,
        data: yearData,
        // nameTextStyle: {
        //   color: "#b8b4b4",
        // },
        axisLabel: {
          color: "#b8b4b4", //字体颜色
          fontSize: 12, //字体大小
        },
      },

      yAxis: {
        type: "value",
        min: "0",
        max: "dataMax",
        // nameTextStyle: {
        //   color: "#b8b4b4",
        // },
        axisLabel: {
          color: "#b8b4b4", //字体颜色
          fontSize: 12, //字体大小
        },
      },
      series: series,
    });
    // console.log("legendData数组", legendData);
    // console.log("series数组", series);
    // console.log("yearData数组", yearData);

    // 监听窗口大小
    window.addEventListener("resize", () => {
      myChart?.resize();
    });
  } else {
    console.log("chart is null");
  }
};

onMounted(() => {
  nextTick(() => {
    getSalaryforYear();
  });
});
</script>
